if (!org) var org={};
if (!org.shmk) org.shmk = {};
if (!org.shmk.fireball) org.shmk.fireball = {};

org.shmk.fireball = {
gmDate: null,
changeDate: false,
team: 'BOS',
interval: 60,
dispUntil: 11,
req: new XMLHttpRequest(),
timerOn: false,
timer: null,
contextToggle: null,

getURL: function(){
	if (this.gmDate == null) {
	    this.setDate();
	}
	if (this.changeDate){
		var tmp = new Date();
		if (tmp.getHours() >= this.dispUntil){
			this.nextDay();
		}
 	}

	var _year = this.gmDate.getFullYear();
	var _month = this.gmDate.getMonth() + 1;
	var _date = this.gmDate.getDate();

	if (_month < 10)
		_month = "0" + _month;
		
	if (_date < 10)
		_date = "0" + _date;

 	return "http://gd2.mlb.com/components/game/mlb/year_" + _year + "/month_" + _month + "/day_" + _date + "/master_scoreboard.xml";
    },

setDate: function(){
	this.gmDate = new Date();
	if (this.gmDate.getHours() < this.dispUntil){
		this.prevDay();
		this.changeDate = true;
	}
    },

prevDay: function(){
	this.gmDate.setDate(this.gmDate.getDate() - 1);
 	this.changeDate = false;
    },

nextDay: function(){
	this.gmDate.setDate(this.gmDate.getDate() + 1);
	this.changeDate = false;
    },
	
startup: function(){
	// XMLHttpRequest requires UniversalBrowserRead privileges.
	// If we can't get that, we're not going to work, so just bail.
	try {
    		netscape.security.PrivilegeManager.enablePrivilege("UniversalBrowserRead");
   	} catch (e) {
    		alert("FireBall: Permission UniversalBrowserRead denied.");
		return;
   	}

	this.req = new XMLHttpRequest();
	var me = this;
	this.req.onload = function() { me.processXml(); };
	this.req.onerror = function() { me.networkError(); };
	this.loadPrefs();
	this.prefObserver.register(this);
	this.setDate();
	this.refreshScore();
	this.startTimer();
    },
	
loadPrefs: function(){
	var prefs = Components.classes["@mozilla.org/preferences-service;1"].getService(Components.interfaces.nsIPrefBranch);
	if (prefs.getPrefType("extensions.fireball.dispTeam") == prefs.PREF_STRING){
		this.team = prefs.getCharPref("extensions.fireball.dispTeam");
	}

	if (prefs.getPrefType("extensions.fireball.dispPrev") == prefs.PREF_INT){
		this.dispUntil = prefs.getIntPref("extensions.fireball.dispPrev");
	}

	if (prefs.getPrefType("extensions.fireball.interval") == prefs.PREF_INT){
		this.interval = prefs.getIntPref("extensions.fireball.interval");
	}
    },

toggleTimer: function(){
	if (this.timerOn){
		this.stopTimer();
	}else{
		this.startTimer();
	}
    },

startTimer: function(){
	if (!this.timerOn){
	    var me = this;
	    this.timer = window.setInterval(function(){me.refreshScore();}, this.interval*1000);
		this.timerOn = true;
		document.getElementById('fireballMenuToggle').label = "Stop Auto Refresh";
	}
    },

stopTimer: function(){
	if (this.timerOn){
		window.clearInterval(this.timer);
		this.timerOn = false;
		document.getElementById('fireballMenuToggle').label = "Start Auto Refresh";			
	}
    },

refreshScore: function(){
	var fullUrl = this.getURL();

	try {
	    this.req.open('GET', fullUrl, true);
	    this.req.send(null);
	}catch(e){
	    alert("Fireball encountered an error while loading MLB scores.\n" + e.description);
	}
    },

clearScores: function(){
	//clear existing scores

	var tips = document.getElementById('fireballtipScores');
	if ( tips != null ) {
	     while (tips.hasChildNodes()) {
	    	 tips.removeChild(tips.firstChild);
	     }		
	}

	var curGame = document.getElementById('fireballtipCurGame');
	if (curGame != null){
		while (curGame.hasChildNodes()){
			curGame.removeChild(curGame.firstChild);
		}
	}

    },

networkError: function(){
	document.getElementById('fireball').label = "FireBall - Network Error";

	var dte = document.getElementById('fireballtipDate');
	dte.value = (this.gmDate.getMonth() + 1) + "/" + this.gmDate.getDate() + "/" + this.gmDate.getFullYear();

	this.clearScores();

	var tips = document.getElementById('fireballtipScores');
	var spacer = document.createElement("spacer");	
 	spacer.setAttribute("height", "2px");		
	var thisScore = document.createElement("description");
	thisScore.setAttribute("value",'No Game Data Available');
	thisScore.setAttribute("style", "font-weight:bold;");
	tips.appendChild(thisScore);
	tips.appendChild(spacer);
    },

processXml: function(){
	var statusSet = false;
	var xmlDoc = this.req.responseXML;

	var games = xmlDoc.getElementsByTagName("game");
	var fireballPanel = document.getElementById('fireball');
	fireballPanel.label = "No " + this.team + " Game";

	var dte = document.getElementById('fireballtipDate');
	dte.value = (this.gmDate.getMonth() + 1) + "/" + this.gmDate.getDate() + "/" + this.gmDate.getFullYear();
	//clear existing scores

	this.clearScores();
	var tips = document.getElementById('fireballtipScores');
	var curGame = document.getElementById('fireballtipCurGame');
	var spacer = document.createElement("spacer");	
 	spacer.setAttribute("height", "2px");		
	var thisScore = document.createElement("description");
	thisScore.setAttribute("value",'SCORES');
	thisScore.setAttribute("style", "font-weight:bold;");
	tips.appendChild(thisScore);
	tips.appendChild(spacer);

	//Calculate the user's time in relation to Eastern.
	//We know Eastern is 4 hours behind UTC, so go from there
	var tmpDate = new Date();
	var hrsBehind = (tmpDate.getTimezoneOffset() / 60) - 4;

	var aTeam, hTeam, aRuns, hRuns, status, str, gametime;
	for (var i=0;i<games.length;i++){

		aTeam = games[i].attributes["away_name_abbrev"].value;
		hTeam = games[i].attributes["home_name_abbrev"].value;
		status = games[i].getElementsByTagName("status")[0].attributes["status"].value;
		var gtArr = games[i].attributes["time"].value.split(":");
		gtArr[0] = gtArr[0] - hrsBehind;
		if (gtArr[0] < 1)
			gtArr[0] = gtArr[0] + 12;
		gametime = gtArr[0] + ":" + gtArr[1];
		if (status == "Preview" || status == "Pre-Game" || status == "Warmup"){
			str = aTeam + " at " + hTeam + " " + gametime;
		}else if (status == "Postponed"){
			str = aTeam + " at " + hTeam + " PPD";
		}else if (status == "Delayed Start" || status == "Delayed"){
			str = aTeam + " at " + hTeam + " DEL";
		}else{
			aRuns = games[i].getElementsByTagName("linescore")[0].getElementsByTagName("r")[0].attributes["away"].value;
			hRuns = games[i].getElementsByTagName("linescore")[0].getElementsByTagName("r")[0].attributes["home"].value;
			if (status == "Final" || status == "Game Over"){
				status = "F/";
			}else{
			  if (games[i].getElementsByTagName("status")[0].attributes["top_inning"].value == "Y"){
				status = "Top ";
			  }else{
				status = "Bot ";
			  }
			}
				
			status = status + games[i].getElementsByTagName("status")[0].attributes["inning"].value;
			str = aTeam + " " + aRuns + " " + hTeam + " " + hRuns + " " + status;
		}
		thisScore = document.createElement("description");
		thisScore.setAttribute("value",str);
		tips.appendChild(thisScore);
		tips.appendChild(spacer);

		if (aTeam == this.team || hTeam == this.team){
			if (!statusSet){
				fireballPanel.label = str;
				statusSet = true;
			}else {
				fireballPanel.label = fireballPanel.label + "  ||  " + str;
			}
			var statusTag = games[i].getElementsByTagName("status")[0];
			var status = statusTag.attributes["status"].value;

			var _title = aTeam + " v. " + hTeam;
			thisScore = document.createElement("description");
			thisScore.setAttribute("value",_title);
			thisScore.setAttribute("style", "font-weight:bold;");
			curGame.appendChild(thisScore);
			curGame.appendChild(spacer);

			if (status == "In Progress"){
				var balls = statusTag.attributes["b"].value;
				var strikes = statusTag.attributes["s"].value;
				var outs = statusTag.attributes["o"].value;
				var bso = balls + "-" + strikes + " " + outs + " outs";
				thisScore = document.createElement("description");
				thisScore.setAttribute("value",bso);
				curGame.appendChild(thisScore);
				curGame.appendChild(spacer);
					
				var batter = "B: " + games[i].getElementsByTagName("batter")[0].attributes["last"].value;
				thisScore = document.createElement("description");
				thisScore.setAttribute("value",batter);
				curGame.appendChild(thisScore);
				curGame.appendChild(spacer);
				
				var pitcher = "P: " + games[i].getElementsByTagName("pitcher")[0].attributes["last"].value;
				thisScore = document.createElement("description");
				thisScore.setAttribute("value",pitcher);
				curGame.appendChild(thisScore);
				curGame.appendChild(spacer);

				var runners = games[i].getElementsByTagName("runners_on_base")[0];
				var _1b = "Empty";
				var _2b = "Empty";
				var _3b = "Empty";

				if (runners.attributes["status"].value != 0){
				if (runners.getElementsByTagName("runner_on_1b").length != 0){
				  _1b = runners.getElementsByTagName("runner_on_1b")[0].attributes["last"].value;
				}
				if (runners.getElementsByTagName("runner_on_2b").length != 0){
				  _2b = runners.getElementsByTagName("runner_on_2b")[0].attributes["last"].value;
				}
				if (runners.getElementsByTagName("runner_on_3b").length != 0){
				  _3b = runners.getElementsByTagName("runner_on_3b")[0].attributes["last"].value;
				}
				}

				_1b = "1: " + _1b;
				_2b = "2: " + _2b;
				_3b = "3: " + _3b;
				thisScore = document.createElement("description");
				thisScore.setAttribute("value",_1b);
				curGame.appendChild(thisScore);
				curGame.appendChild(spacer);
				thisScore = document.createElement("description");
				thisScore.setAttribute("value",_2b);
				curGame.appendChild(thisScore);
				curGame.appendChild(spacer);
				thisScore = document.createElement("description");
				thisScore.setAttribute("value",_3b);
				curGame.appendChild(thisScore);
				curGame.appendChild(spacer);
				
			}else if (status == "Preview" || status == "Pre-Game" || status == "Warmup"){
				
				thisScore = document.createElement("description");
				thisScore.setAttribute("value",gametime);
				curGame.appendChild(thisScore);
				curGame.appendChild(spacer);

				if (status == "Preview"){
				  var _line = games[i].attributes["away_name_abbrev"].value + ": ";
				  _line = _line + games[i].getElementsByTagName("away_probable_pitcher")[0].attributes["last"].value;
				  thisScore = document.createElement("description");
				  thisScore.setAttribute("value",_line);
				  thisScore.setAttribute("style","font-family:monospace");
				  curGame.appendChild(thisScore);
				  curGame.appendChild(spacer);

				  _line = games[i].attributes["home_name_abbrev"].value + ": ";
				  _line = _line + games[i].getElementsByTagName("home_probable_pitcher")[0].attributes["last"].value;
				  thisScore = document.createElement("description");
				  thisScore.setAttribute("value",_line);
				  thisScore.setAttribute("style","font-family:monospace");
				  curGame.appendChild(thisScore);
				  curGame.appendChild(spacer);
				}
			}else if (status == "Final" || status == "Game Over"){
				var linescoreElt = games[i].getElementsByTagName("linescore")[0];

				var aRuns = linescoreElt.getElementsByTagName("r")[0].attributes["away"].value;
				var aHits = linescoreElt.getElementsByTagName("h")[0].attributes["away"].value;
				var aErrs = linescoreElt.getElementsByTagName("e")[0].attributes["away"].value;
				var awayLine = aTeam;
				if (aTeam.length == 2)
					awayLine = awayLine + " ";
				awayLine = awayLine + ": ";
				if (aRuns < 10 && hRuns > 10)
					awayLine = awayLine + " ";
				awayLine = awayLine + aRuns + " ";
				if (aHits < 10 && hHits > 10)
					awayLine = awayLine + " ";
				awayLine = awayLine + aHits + " ";
				if (aErrs < 10 && hErrs > 10)
					awayLine = awayLine + " ";
				awayLine = awayLine + aErrs + " ";

				var hRuns = linescoreElt.getElementsByTagName("r")[0].attributes["home"].value;
				var hHits = linescoreElt.getElementsByTagName("h")[0].attributes["home"].value;
				var hErrs = linescoreElt.getElementsByTagName("e")[0].attributes["home"].value;
				var homeLine = hTeam;
				if (hTeam.length == 2)
					homeLine = homeLine + " ";
				homeLine = homeLine + ": ";
				if (hRuns < 10 && aRuns > 10)
					homeLine = homeLine + " ";
				homeLine = homeLine + hRuns + " ";
				if (hHits < 10 && aHits > 10)
					homeLine = homeLine + " ";
				homeLine = homeLine + hHits + " ";
				if (hErrs < 10 && aErrs > 10)
					homeLine = homeLine + " ";
				homeLine = homeLine + hErrs + " ";
				
				thisScore = document.createElement("description");
				thisScore.setAttribute("value",awayLine);
				thisScore.setAttribute("style","font-family:monospace");
				curGame.appendChild(thisScore);
				curGame.appendChild(spacer);
				
				thisScore = document.createElement("description");
				thisScore.setAttribute("value",homeLine);
				thisScore.setAttribute("style","font-family:monospace");
				curGame.appendChild(thisScore);
				curGame.appendChild(spacer);

				thisScore = document.createElement("description");
				thisScore.setAttribute("value", "Final\/" + games[i].getElementsByTagName("status")[0].attributes["inning"].value);
				thisScore.setAttribute("style","font-family:monospace");
				curGame.appendChild(thisScore);
				curGame.appendChild(spacer);

				thisScore = document.createElement("description");
				pitcher = games[i].getElementsByTagName("winning_pitcher")[0];

				thisScore.setAttribute("value", "W: " + pitcher.attributes["last"].value + " (" + pitcher.attributes["wins"].value + "-" + pitcher.attributes["losses"].value + ")");
				thisScore.setAttribute("style","font-family:monospace");
				curGame.appendChild(thisScore);
				curGame.appendChild(spacer);

				thisScore = document.createElement("description");
				pitcher = games[i].getElementsByTagName("losing_pitcher")[0];

				thisScore.setAttribute("value", "L: " + pitcher.attributes["last"].value + " (" + pitcher.attributes["wins"].value + "-" + pitcher.attributes["losses"].value + ")");
				thisScore.setAttribute("style","font-family:monospace");
				curGame.appendChild(thisScore);
				curGame.appendChild(spacer);
				
				if (games[i].getElementsByTagName("save_pitcher").length > 0){
				   if (games[i].getElementsByTagName("save_pitcher")[0].attributes["last"].value != ""){
					thisScore = document.createElement("description");
					thisScore.setAttribute("value", "S: " + games[i].getElementsByTagName("save_pitcher")[0].attributes["last"].value + " (" + games[i].getElementsByTagName("save_pitcher")[0].attributes["saves"].value + ")");
					thisScore.setAttribute("style","font-family:monospace");
					curGame.appendChild(thisScore);
					curGame.appendChild(spacer);	
				   }
				}
			}
		}
	}
    },

prefObserver: {
    register: function(owner) {
	    this.container = owner;
	    var prefService = Components.classes["@mozilla.org/preferences-service;1"].getService(Components.interfaces.nsIPrefService);
	    this._branch = prefService.getBranch("extensions.fireball.");
	    this._branch.QueryInterface(Components.interfaces.nsIPrefBranch2);
	    this._branch.addObserver("", this, false);
	},

    unregister: function(){
	    if(!this._branch) return;
	    this._branch.removeObserver("", this);
	},

    observe: function(aSubject, aTopic, aData){
	    if(aTopic != "nsPref:changed") return;
	    var prefs = Components.classes["@mozilla.org/preferences-service;1"].getService(Components.interfaces.nsIPrefBranch);
		
	    // aSubject is the nsIPrefBranch we're observing (after appropriate QI)
	    // aData is the name of the pref that's been changed (relative to aSubject)
	    switch (aData) {
	    case "dispTeam":
		if (prefs.getPrefType("extensions.fireball.dispTeam") == prefs.PREF_STRING){
		    this.container.team = prefs.getCharPref("extensions.fireball.dispTeam");
		}
		this.container.refreshScore();
		break;
	    case "dispPrev":
		if (prefs.getPrefType("extensions.fireball.dispPrev") == prefs.PREF_INT){
		    this.container.dispUntil = prefs.getIntPref("extensions.fireball.dispPrev");
		}
		this.container.setDate();
		this.container.refreshScore();
		break;
	    case "interval":
		if (prefs.getPrefType("extensions.fireball.interval") == prefs.PREF_INT){
		    this.container.interval = prefs.getIntPref("extensions.fireball.interval");
		}
		if (this.container.timerOn){
		    this.container.toggleTimer();
		}
		this.container.toggleTimer();
		break;
	    }
	}
}
}

    window.addEventListener("load", function(e) { org.shmk.fireball.startup(); }, false);